import React, { Component } from "react";

export default class Select2 extends Component {
  constructor() {
    super();
    this.state = { //把树形结构 降维处理
      cityList: [],
      townList: [],
      list: [
        {id:1,name:"湖北",pid:0},//parentid
        {id:2,name:"武汉",pid:1},
        {id:3,name:"荆州",pid:1},
        {id:4,name:"洪山",pid:2},
        {id:5,name:"江夏",pid:2},
        {id:6,name:"沙市",pid:3},
        {id:7,name:"松滋",pid:3},

        {id:8,name:"河南",pid:0},
        {id:9,name:"郑州",pid:8},
        {id:10,name:"金水区",pid:9},
        {id:11,name:"新郑",pid:9},
        {id:12,name:"洛阳",pid:8},
        {id:13,name:"洛阳的区一",pid:12},
        {id:14,name:"洛阳的区二",pid:12}

      ],
    };
  }
  provinceChange = (id) => {
    //console.log(typeof id);
    if (id) {
      //省份的编号  跟进省份的编号 找到对应的城市
      this.setState({
        townList:[],
        cityList: this.state.list.filter((item) => item.pid == id), 
      });
    } else {
      this.setState({
        cityList: [],
        townList:[]
      });
    }
  };
  cityChange = (id) => {
    if (id) {
      this.setState({
        townList: this.state.list.filter((item) => item.pid == id),
      });
    }else{
      this.setState({
        townList:[]
      })
    }
  };

  render() {
    return (
      <div>
        <select
          onChange={(e) => {
            this.provinceChange(e.target.value);
          }}
        >
          <option value="">请选择省份</option>
          {this.state.list.filter(item=>item.pid===0).map((item) => {
            return (
              <option key={item.id} value={item.id}>
                {item.name}
              </option>
            );
          })}
        </select>
        <select
          onChange={(e) => {
            this.cityChange(e.target.value);
          }}
        >
          <option value="">请选择城市</option>
          {this.state.cityList.map((item) => {
            return (
              <option key={item.id} value={item.id}>
                {item.name}
              </option>
            );
          })}
        </select>
        <select>
          <option value="">请选择区县</option>
          {this.state.townList.map((item) => {
            return (
              <option key={item.id} value={item.id}>
                {item.name}
              </option>
            );
          })}
        </select>
      </div>
    );
  }
}
